<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Order as OrderService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderException as OrderExceptionService;
use app\common\service\OrderMaterial as OrderMaterialService;
class OrderException extends Admin {
	/**
	 * 亏损详 细
	 * @param integer $mid
	 * @param integer $orderMaterialId
	 */
	public function detail(){
		$orderId = $this->request->param('order_id/d', 0);
		if ($this->request->isAjax()) {
			$orderExceptionService=new OrderExceptionService();
			$orderMaterialService=new OrderMaterialService();
			$orderSizeService=new OrderSizeService();
			$materialStockCuttingService=new MaterialStockCuttingService();
			$orderMaterialItemService=new OrderMaterialItemService();
			$list=$orderExceptionService->getListByOrderId($orderId);

			foreach ($list as $key => $value) {
				$list[$key]['omInfo']=$omInfo=$orderMaterialService->getInfoByOrderIdMaterialId($orderId, $value['material_id'], "mid,material_id,weight,checkcloth_length,weight_shrink,billing_caigou_count,billing_caigou_kgcount,yingcai_count,caichuang_strip_dosage,caichuang_wheat_height_length,caichuang_wheat_low_length,tiaoshu,weight_page");
				$list[$key]['omInfo']['shiji_weight_shrink']=$omInfo['weight_shrink']-$omInfo['weight_page'];
				$osList=$orderSizeService->getListByOrderId($orderId);
				$list[$key]['shicai_count']=$shicaiCount = array_sum(array_column($osList, 'shicai_count'));
				$mscInfo = $materialStockCuttingService->getInfoByMaterialId($orderId, $value['material_id']);
				$omiList=$orderMaterialItemService->getListByOrderMaterialId($omInfo['mid']);

				$heightTotal = array_sum(array_column($omiList, 'caichuang_t_wheat_height'))+arrayGet($mscInfo, 'caichuang_t_wheat_height', 0);
				$lowTotal = array_sum(array_column($omiList, 'caichuang_t_wheat_low'))+arrayGet($mscInfo, 'caichuang_t_wheat_height', 0);
				$neadendTotal = array_sum(array_column($omiList, 'caichuang_t_neadend'))+arrayGet($mscInfo, 'caichuang_t_neadend', 0);
				$stripTotal = array_sum(array_column($omiList, 'caichuang_t_strip'))+arrayGet($mscInfo, 'caichuang_t_strip', 0);
				$allStripDosage=$omInfo['caichuang_strip_dosage']*$shicaiCount;
				$list[$key]['caichuang_after']=$labuLenght=round(($heightTotal*$omInfo['caichuang_wheat_height_length']) + ($lowTotal*$omInfo['caichuang_wheat_low_length']) + $neadendTotal + $stripTotal + $allStripDosage + ($heightTotal+$lowTotal)*0.06, 2);//拉布米长
				$where=[
					['order_id', '=' ,$orderId],
					['material_id', '=' ,$value['material_id']],
					['type', '=' ,2]
				];
				$trueWeight= db('checkcloth_shrink')->where($where)->value("sum(true_weight)");
				$list[$key]['vWeight']=$omInfo['tiaoshu']==0?0:$trueWeight/$omInfo['tiaoshu'];
				$list[$key]['type']= arrayGet(config('mimo.exception_type'), $value['type'],'') ;

			}
			$data['data']=$list;
			$data['code']=0;
			$data['msg']='';
			return json($data);
		}
		$assign = [
    		'orderId'=>$orderId
    	];
    	return $this->assign($assign)->fetch();
	}
	/**
	 * 更改亏损状态
	 * @author 飞燕
     * @date 2021年4月3日
	 * @param integer $mid
	 * @param integer $orderMaterialId
	 */
	public function status(){
		$id  = $this->request->param('id/d', 0);
		$orderService=new OrderService();
		$orderExceptionService=new OrderExceptionService();
		$oeInfo = $orderExceptionService->getInfoById($id);
		if(!$oeInfo) return $this->error("数据异常");
		try {
    		db()->startTrans();
			$oud = [
	    		'update_time' => time(),
				'status' => 1,
	    		'process_time' => time(),
	    	];
			$res = db('order_exception')->where('id', $id)->update($oud);
			$orderService->updateExceptionNum($oeInfo['order_id']);
			$this->addOrderLog($oeInfo['order_id'], '', "修改物料".getMaterialName($oeInfo['material_id'])."损耗状态[{$oeInfo['type']}]");
			db()->commit();

	    	return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
	}

    /**
     * 导入历史订单信息
     */
    public function importMesOrder(){
        $post = $this->request->param();
        $imprtDates=$this->request->param('importday', '');

        if ($this->request->isAjax()) {
            $betweentimes=[strtotime($post['importday'].' 00:00:00'),strtotime($post['importday'].' 23:59:59')];
            $needImpdayInfo=db('order a')
                ->field('count(a.id),count(a.id) as order_count,a.id,a.sku,a.is_auto_import,a.status,a.client_ordernum as client_ordernum,DATE_FORMAT(FROM_UNIXTIME(a.create_time),"%Y-%m-%d %H:28:00") as importdate')
                ->where("is_auto_import=1 and a.status<99 and a.create_time between $betweentimes[0] and $betweentimes[1]")->orderRaw('count(a.id) desc')
                ->group('DATE_FORMAT(FROM_UNIXTIME(a.create_time),"%Y-%m-%d-%H")')->select();
            $minhuifang=db('order a')
                ->field('count(a.id),count(a.id) as order_count,a.id,a.sku,a.is_auto_import,a.status,a.client_ordernum as client_ordernum,DATE_FORMAT(FROM_UNIXTIME(a.create_time),"%Y-%m-%d %H:28:00") as importdate')
                ->where("is_auto_import=2 and a.status<99 and a.create_time between $betweentimes[0] and $betweentimes[1]")->find();

            $heighhour=!empty($needImpdayInfo) ? $needImpdayInfo[0]['importdate'] : '';
            $ordernum=!empty($needImpdayInfo) ? $needImpdayInfo[0]['client_ordernum'] : '';
            $heighhourCount=!empty($needImpdayInfo) ? $needImpdayInfo[0]['order_count'] :0;
            $dataArr=['importday'=>$imprtDates,'heighhour'=>$heighhour,'heighhourCount'=>$heighhourCount,'ordernum'=>$ordernum,'count'=>array_sum(array_column($needImpdayInfo,'order_count')),'mighuifang'=>$minhuifang['order_count']];
            $betweentimes=[strtotime($post['importday'].' 00:00:00'),strtotime($post['importday'].' 23:59:59')];
            $datalist=$dataArr;
            return $this->Json(1,json_encode($dataArr),$datalist);
        }
        $orderId=0;
        $assign = [
            'orderId'=>$orderId
        ];
        return $this->assign($assign)->fetch();
    }

	/**
     * 保存损耗备注
     *
     * @author 飞燕
     * @date 2021年4月3日
     *
     */
    public function remark() {
    	$id       = $this->request->param('id/d', 0);
    	$remark   = $this->request->param('remark/s', '');
		$orderExceptionService=new OrderExceptionService();
		$oeInfo = $orderExceptionService->getInfoById($id);
		if(!$oeInfo)			return $this->error("数据异常");
    	$upData = [
    		'remark' => $remark,
    		'update_time' => time(),
    	];
		$ret = db('order_exception')->where('id', $id)->update($upData);
		$this->addOrderLog($oeInfo['order_id'], '', "修改物料".getMaterialName($oeInfo['material_id'])."损耗[{$oeInfo['type']}]备注[{$remark}]");
    	if ($ret) {
    		return $this->Json(1, '保存备注信息成功');
    	} else return $this->Json(0);
    }

    /**
     * 一键启动物料损耗状态
     *
     * @author King
     * @date 2021年9月2日
     *
     */
	public function start_up(){
		$orderId       = $this->request->param('order_id/d', 0);
		$orderService=new OrderService();
		try {
    		db()->startTrans();
			$oud = [
	    		'update_time' => time(),
				'status' => 1,
	    		'process_time' => time(),
	    	];
			$res = db('order_exception')->where('order_id', $orderId)->update($oud);
			$orderService->updateExceptionNum($orderId);
			$this->addOrderLog($orderId, '', "一键启动物料损耗状态");
			db()->commit();
	    	return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
	}
}
